package com.xiaoxu.media.controller;

import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.xiaoxu.base.model.RestResponse;
import com.xiaoxu.media.model.dto.UploadFileParamsDto;
import com.xiaoxu.media.service.MediaFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author xiaoxu
 * @version 1.0
 * @description 大文件上传接口
 * @date 2023/1/22 15:23
 */
@Api(value = "大文件上传接口", tags = "大文件上传接口")
@RestController
public class BigFilesController {

    final
    MediaFileService mediaFileService;

    public BigFilesController(MediaFileService mediaFileService) {
        this.mediaFileService = mediaFileService;
    }


    @ApiOperation(value = "文件上传前检查文件")
    @PostMapping("/upload/checkfile")
    public RestResponse<Boolean> checkFile(@RequestParam("fileMd5") String fileMd5) {
        return mediaFileService.checkFile(fileMd5);
    }


    @ApiOperation(value = "分块文件上传前的检测")
    @PostMapping("/upload/checkchunk")
    public RestResponse<Boolean> checkChunk(@RequestParam("fileMd5") String fileMd5,@RequestParam("chunk") int chunk) {
        return mediaFileService.checkChunk(fileMd5,chunk);
    }

    @ApiOperation(value = "上传分块文件")
    @PostMapping("/upload/uploadchunk")
    public RestResponse uploadChunk(
            @RequestParam("file") MultipartFile file,
            @RequestParam("fileMd5") String fileMd5,
            @RequestParam("chunk") int chunk
    ) throws Exception {
        return mediaFileService.uploadChunk(fileMd5,chunk, file.getBytes());
    }

    @ApiOperation(value = "合并文件")
    @PostMapping("/upload/mergechunks")
    public RestResponse mergeChunks(
            @RequestParam("fileMd5") String fileMd5,
            @RequestParam("fileName") String fileName,
            @RequestParam("chunkTotal") int chunkTotal
    ) {
        Long companyId = 1232141425L;
        UploadFileParamsDto params = new UploadFileParamsDto();
        params.setFileType("001002");
        params.setTags("课程视频");
        params.setRemark("");
        params.setFilename(fileName);
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(fileName);
        String mimeType = extensionMatch.getMimeType();
        params.setContentType(mimeType);

        return mediaFileService.mergeChunks(companyId,fileMd5,chunkTotal,params);
    }


}
